package com.buka.interceptor;

import cn.hutool.core.util.StrUtil;
import com.buka.common.BizCodeEnum;
import com.buka.util.CommonUtil;
import com.buka.util.JWTUtil;
import com.buka.util.JsonData;
import com.buka.vo.LoginUserVo;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
public class LoginUserInterceptor implements HandlerInterceptor {

    //类似map 集合  key 是线程id  value 存储的内容
    public static ThreadLocal<LoginUserVo> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if (token != null) {
            Claims claims = JWTUtil.checkJWT(token);
            if (null != claims) {
                //身份认证通过
                LoginUserVo loginUserVo = new LoginUserVo();
                Long id = claims.get("id", Long.class);
                loginUserVo.setId(id);

                String name = claims.get("name", String.class);
                loginUserVo.setName(name);

                String mail = claims.get("mail", String.class);
                loginUserVo.setMail(mail);

                String headImage = claims.get("head_image", String.class);
                loginUserVo.setHeadImg(headImage);


                String deviceInfo = claims.get("deviceInfo", String.class);
                //校验设备信息
                String deviceInfo1 = CommonUtil.getDeviceInfo(request);
                if(!StrUtil.equals(deviceInfo1,deviceInfo)){
                    JsonData jsonData = JsonData.buildResult(BizCodeEnum.DIFF_ADDR);
                    CommonUtil.sendErrorMessage(response,jsonData);
                    return false;
                }

                //怎么向下传递呢？
                threadLocal.set(loginUserVo);
                return true;

            }
        }
        CommonUtil.sendErrorMessage(response, JsonData.buildResult(BizCodeEnum.NOT_LOGIN));
        return false;

    }
}
